package dao

import (
	"fmt"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/downloadlogs"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
)

// -------------------- dao层 - 下载文件日志相关操作 -----------------------//

type DownloadLogsDao struct {
}

func NewDownloadLogsDao() *DownloadLogsDao {
	return &DownloadLogsDao{}
}

// InsertDownloadLogs            新增下载日志
func (d *DownloadLogsDao) InsertDownloadLogs(m *downloadlogs.DownloadLogsModel) *dingo.ErrorWrap {

	db := global.Orm.Table("download_log").Create(m)
	return dingo.ErrorIf(db.Error, true)
}

// GetDownloadLogsList            下载日志查询列表
func (d *DownloadLogsDao) GetDownloadLogsList(param *request.FileDownLogsListReq) *dingo.ErrorWrap {
	var (
		lst    []downloadlogs.DownloadLogsList
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)
	db := global.Orm.Table("download_log l").
		Select("l.*", "u.phone as user_phone,u.name,u.user_name as u_name", "r.name as role_name").
		Joins("LEFT JOIN users u ON l.user_id = u.id").
		Joins("LEFT JOIN roles r ON u.role_id = r.id")
	if param.Name != "" { db.Where("u.name like ?", fmt.Sprint("%", param.Name, "%")) }
	if param.LoginIp != "" { db.Where("l.client_ip = ?", param.LoginIp) }
	if param.UserPhone != "" { db.Where("u.phone = ?", param.UserPhone) }
	if param.Remark != "" { db.Where("l.remark like ?", fmt.Sprint("%", param.Remark, "%")) }
	db.Order("l.create_at desc")
	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)

	return dingo.ErrorIf(db.Error, lst, count)
}
